package com.caipin.utils;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2021-10-06 12:35
 * @Description: TODO
 */
public class ImageUtils {
    private static String ImageFormat = "jpg";

    public static String resizeImage(String filePath, int maxSize, int w, int h) {
        try {
            BufferedImage src = fileToBufferedImage(filePath);
            BufferedImage output = Thumbnails.of(new BufferedImage[] { src }).size(w, h).asBufferedImage();
            String base64 = imageToBase64(output);
            while (base64.length() - base64.length() / 8 * 2 > maxSize * 1000) {
                output = Thumbnails.of(new BufferedImage[] { output }).scale(0.8999999761581421D).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return imageToBase64(output);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static BufferedImage fileToBufferedImage(String filePath) throws Exception {
        FileInputStream is = new FileInputStream(filePath);
        BufferedImage img = ImageIO.read(is);
        return img;
    }

    public static BufferedImage base64String2BufferedImage(String base64string) {
        BufferedImage image = null;
        try {
            InputStream stream = base64StringToInputStream(base64string);
            image = ImageIO.read(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    private static InputStream base64StringToInputStream(String base64string) {
        Base64.Decoder decoder = Base64.getDecoder();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decoder.decode(base64string));
        InputStream inputStream = byteArrayInputStream;
        return inputStream;
    }

    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64.Encoder encoder = Base64.getEncoder();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, ImageFormat, baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(encoder.encode(baos.toByteArray()));
    }
}
